<?php
class ReportService{
    //输入类型
    const NONE = 0;
    const TEXT = 1;
    const SELECT = 2;
    const RANGE = 3;
    public function getValueByEles($uid,$items,$type = array(EvaluateReportLog::TYPE_YJX,EvaluateReportLog::TYPE_USER))
    {
        if(!is_array($items)){
            return false;
        }
        //转换
        $name = array();
        $map = array();
        foreach ($items as $key => $it) {
            array_push($name, $it["name"]);
            $map[$it["name"]] = $it["field_name"];
        }
        
        $ret = EvaluateReportLog::model()->findByAttributes(array(
                "uid"=>$uid,"type"=>$type,),
                array("order"=>"id desc"));
        if($ret === null){
            return array();
        }
        $ret = EvaluateReportCache::model()->findAllByAttributes(
                array("no"=>$ret->no,"name"=>$name));
        $rets = array();
        foreach ($ret as $it) {
            $item["name"]=$it->name;
            $item["value"]=$it->value;
            $item["issue"]=$it->issue=="↑"?1:0;
            $item["normal"]=$it->normal;
            $item["unit"]=$it->unit;
            
            $rets[$map[$it->name]] = $item;
        }
        return $rets;
    }
    /**
     * 
     * @param array $items 体检项目
     * @return boolean
     */
    public function saveQuestionItems($uid,$items)
    {
        $trans = Yii::app()->db->beginTransaction();
        try {
            $ret = EvaluateReportLog::model()->findByAttributes(array("uid"=>$uid,"type"=>  EvaluateReportLog::TYPE_FXPG),array("order"=>"id desc"));
            if($ret === null){
                $ret = new EvaluateReportLog();
                $ret->type = EvaluateReportLog::TYPE_FXPG;
                $ret->uid = $uid;
                if($ret->save()===false){
                    return false;
                }
                $iid = sprintf("%06d",$ret->id);
                $ret->no = date("YmdHis").$iid;
                if($ret->update()===false){
                    throw new Exception("新建风险评估体检项目保存记录");
                }
            }
            foreach ($items as $key => $it) {
                $item = $this->getReportInfo($key);
                if($item!=null){
                    $item["value"] = $it;
                }
                $t = EvaluateReportCache::model()->findByAttributes(array(
                    "uid"=>$uid,
                    "no"=>$ret->no,
                    "name"=>$item["name"],
                    "parent_name"=>$item["parent_name"]
                ));
                if($t === null){
                    $t = new EvaluateReportCache();
                    $t->uid = $uid;
                    $t->no = $ret->no;
                    $t->name = $item["name"];
                    $t->value = $item["value"];
                    $t->parent_name = $item["parent_name"];
                    $t->issue = $this->getIssue($item["value"],$item["normal"]);
                    $t->normal = $item["normal"];
                    $t->unit = $item["unit"];
                    if(false === $t->save()){
                        throw new Exception("保存体检项失败");
                    }
                }else{
                    $t->value = $item["value"];
                    $t->issue = $this->getIssue($item["value"],$item["normal"]);
                    if(false === $t->update()){
                        throw new Exception("保存体检项失败");
                    }
                }
            }
            $trans->commit();
        } catch (Exception $exc) {
            $trans->rollback();
            return false;
        }
        return true;
    }
    /**
     * 保存体检项目
     */
    public function saveUserReport($uid,$no,$items)
    {
        $sql="INSERT INTO evaluate_report_cache (`uid`,`no`,`parent_name`,"
                . "`name`,`value`,`issue`,`normal`,`unit`) VALUES";
            foreach($items as $it){
                $value = $it["value"];
                $normal = isset($it["normal"])?$it["normal"]:"";
                
                if(strpos($normal, "~")!==false){
                    
                    $v = explode("~", $normal);
                    if((float)$value<(float)$v[0]){
                        $it["issue"] = "↓";
                    }elseif((float)$value>(float)$v[1]){
                        $it["issue"] = "↑";
                    }
                }
                $issue = isset($it["issue"])?$it["issue"]:"";
                $unit = isset($it["unit"])?$it["unit"]:"";
                $sql .= "('$uid','$no','{$it["parent_name"]}','{$it["name"]}','$value',"
                        . "'$issue','$normal','$unit'),";
            }
            
            
            if(count($items)){
                $num=Yii::app()->db->createCommand(substr($sql,0,-1))->execute();
                if($num){
                    return true;
                }
            }
            return false;
    }


    /*
     * 插入体检报告之前处理数据
     */
    public function insertUserReportBefore($saveitems){
        //获取体检大项目名称
    	$arrProgram=array();
    	foreach($saveitems as $key=>$val){
    		array_push($arrProgram, $val["parent_name"]);
    		
    	}
        $arrProgram = array_unique($arrProgram);
        $arrResult=array();
        foreach($arrProgram as $key=>$val){
            $arr = array(
                "parentName"=>$val,
                "itemSet"=>array()
                );
            array_push($arrResult, $arr);

        }
        // var_dump($arrResult);exit();
        // //
        // var_dump($arrProgram);
        $itemsResult =array();
        // var_dump($saveitems);exit();

        foreach ($arrResult as $k => $v) {
           
            foreach($saveitems as $key=>$val){
                if($v["parentName"]==$val["parent_name"]){
                    // echo "这里";continue;
                    array_push($v["itemSet"], $val);
                    // var_dump($v);continue;
                }






            }
            array_push($itemsResult, $v);
        }
        return $itemsResult;
        // exit();
        // var_dump($arrResult);exit();
        var_dump($itemsResult);exit();
        // var_dump($arrProgram);exit();
    	// var_dump($saveitems);exit();
    	
    	
    }

    private function getRandNum(){
        $authnum="";
        for($i=0;$i<6;$i++){
            $randnum=rand(0,9); // 10+26;
            $authnum.=$randnum;
        }
        $authnum="zj".$authnum;
        return $authnum;
    }
    /*
     * 
     * 
     * 插入体检报告到小人项目的数据库
     *@param  $arrayItemResult 体检报告数据
    @return 反回小人体检报告的reportid
     */
    public function insertUserReport($reportinfo,$arrayItemResult){
    	 // $mysqli = new mysqli('127.0.0.1', 'root', '', 'report');
        $mysqli = new mysqli('115.28.14.33', 'root', 'ins', 'report');
        if ( mysqli_connect_errno ()) {
//            printf ( "Connect failed: %s\n" ,  mysqli_connect_error ());
            return false;
        }
        $mysqli->query("set names utf8");
        // var_dump($arrayItemResult);exit();

       $realname = $reportinfo["realname"];
       $examdate = $reportinfo["examdate"];
       // $examid =   $reportinfo["examid"];
////        var_dump($examid);exit();
//        $password =  $reportinfo["password"];

//        $genderNo = 0;
       if ($reportinfo["gender"] == '男') {
           $genderNo = 1;
       }else if ($reportinfo["gender"] == '女') {
           $genderNo = 2;
       }
        // $realname="";
        // $examdate = "2014-04-10";
        // $genderNo="2";
        $examid=$this->getRandNum();
        $password=$this->getRandNum();
        // $evaluate_report_cache = new EvaluateReportCache();
        // $eca
        
        $infosql=<<<EOF
            insert into `report`.`reportinfo` (`username`,`gender`,`examtime`,`examid`,`password`) values("$realname","$genderNo","$examdate","$examid","$password")
EOF;
        $mysqli -> query ( $infosql );
        $reportid = $mysqli->insert_id;
        
        if(isset($arrayItemResult['data'])){
            $arrayItemResult=$arrayItemResult['data'];
        }
        // var_dump($arrayItemResult);exit();
        foreach ($arrayItemResult as $parent)
        {
            if ($parent["parentName"] == "basic") {
                continue;
            }

            $parentName = $parent["parentName"];
            $parentsql = "insert into report.programinfo(reportid, programname) values($reportid, '"."$parentName')";

            $mysqli -> query ( $parentsql );
            $programid = $mysqli->insert_id;


            $itemSet = $parent["itemSet"];
            foreach ($itemSet as $item) {
                $itemname = trim($item["name"]);
                $result = trim($item["value"]);
                //单位
                if(array_key_exists("unit", $item)){
                    $unit = trim($item["unit"]);
                }else{
                    $unit="";
                }
                
                //范围
                if(array_key_exists("normal", $item)){
                    $normal = trim($item["normal"]);
                }else{
                    $normal="";
                }
//                $normal = $item["normal"];
                //异常
                if(array_key_exists("issue", $item)){
                    $issue = ($item['issue']);
                }else{
                    $issue="";
                }
//                $issue = $item["issue"];
                $itemsql = "insert into report.iteminfo(reportid,programid,itemname,result,unit,normal,issue) values($reportid, $programid, '$itemname', '$result', '$unit', '$normal','$issue')";
                $mysqli -> query ( $itemsql );
            }
        }
        return $reportid;
    		
    }
    
    
    /**
     * 
     * @param type $disids
     * @return boolean
     */
    private function getIssue($value,$normal)
    {
        $v = explode("~", $normal);

        if(count($v)!=2){
            return "";
        }
        if($value>$v[1]){
            return "↑";
        }elseif($value<$v[0]){
            return "↓";
        }else{
            return "";
        }
    }
    public function getDiseaseReportTemplate($disids = array())
    {
        if(!is_array($disids)){
            return false;
        }
//        var_dump($disids);exit();
        if(count($disids)==0){
            $ret = EvaluateDiseaseType::model()->findAll();
            foreach ($ret as $it) {
                array_push($disids, $it->id);
            }
        }
        $items = array();
        foreach ($disids as $did){
            switch ($did){
                case Disease::GAOXUEYA:
                    $items['blood_triglycerides'] = $this->getReportInfo('blood_triglycerides');
                    break;
                case Disease::GUANXINBING:
                    $items['blood_triglycerides'] = $this->getReportInfo('blood_triglycerides');
                    break;
                case Disease::NAOZUZHONG:
                    $items['blood_triglycerides'] = $this->getReportInfo('blood_triglycerides');
                    break;
                case Disease::TANGNIAOBING;
                    $items['blood_triglycerides'] = $this->getReportInfo('blood_triglycerides');
                    $items['blood_sugar'] = $this->getReportInfo('blood_sugar');
                    break;
                default :
                    break;
            }
        }
  
        return $items;
    }
    private function getReportInfo($itemname) 
    {
        $items['blood_triglycerides'] = array(
            "name" => "甘油三酯",
            "parent_name"=>"血生化",
            "value" => "", 
            "issue" => 0, 
            "normal" => "0.51~1.70",
            "unit" => "mmol/L");
        $items['blood_sugar'] = array(
            "name" => "空腹血糖",
            "parent_name"=>"血生化",
            "value" => "",
            "issue" => 0,
            "normal" => "3.61~6.11",
            "unit" => "mmol/L");
        return isset($items[$itemname]) ? $items[$itemname] : array();
    }
    /**
     * 获取体检报告录入信息
     */
    public function getReportList()
    {

        $items[] = array("name"=>"身高", "parent_name"=>"一般性检查","type"=>  ReportService::SELECT,"option"=>"70~240","unit"=>"cm","default"=>175);
        $items[] = array("name"=>"体重", "parent_name"=>"一般性检查","type"=>  ReportService::SELECT,"option"=>"20~150","unit"=>"kg","default"=>70);
        $items[] = array("name"=>"收缩压", "parent_name"=>"一般性检查","type"=>  ReportService::SELECT,"option"=>"70~200","default"=>110,"unit"=>"mmHg","normal"=>"90~139");
        $items[] = array("name"=>"舒张压", "parent_name"=>"一般性检查","type"=>  ReportService::SELECT,"option"=>"30~180","default"=>70,"unit"=>"mmHg","normal"=>"60~89");


        /*血生化*/
        $items[] = array("name"=>"空腹血糖", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"mmol/L","normal"=>"3.61~6.11","step"=>0.01,"option"=>"2.0~15.0","default"=>5.5);
        $items[] = array("name"=>"总胆固醇", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"mmol/L","normal"=>"2.86~5.98","step"=>0.01,"option"=>"2.0~15.0","default"=>4.5);
        $items[] = array("name"=>"甘油三酯", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"mmol/L","normal"=>"0.51~1.70","step"=>0.01,"option"=>"0.0~3.0","default"=>1.0);
        $items[] = array("name"=>"丙氨酸氨基转移酶（ALT）", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"U/L","normal"=>"0~40","step"=>1,"option"=>"0~50","default"=>20);
        $items[] = array("name"=>"天冬氨酸氨基转移酶", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"U/L","normal"=>"0~40","step"=>1,"option"=>"0~50","default"=>20);
        $items[] = array("name"=>"尿酸", "parent_name"=>"血生化","type"=>  ReportService::RANGE,"unit"=>"umol/L","normal"=>"90~355","step"=>5,"option"=>"50~450","default"=>200);

        /*尿常规*/
        $items[] = array("name"=>"尿白细胞", "parent_name"=>"尿常规","type"=>  ReportService::RANGE,"unit"=>"hp","normal"=>"0~5","step"=>0.1,"option"=>"-1.5~6.5");
        $tiems[] = array("name"=>"尿红细胞","parent_name"=>'尿常规',"type"=>ReportService::TEXT);
        $items[] = array("name"=>"尿比重", "parent_name"=>"尿常规","type"=>  ReportService::RANGE,"unit"=>"","normal"=>"1.003~1.030","step"=>0.001,"option"=>"0.995~1.038");
        $items[] = array("name"=>"尿酸碱度", "parent_name"=>"尿常规","type"=>  ReportService::RANGE,"unit"=>"","normal"=>"4.0~8.5","step"=>0.01,"option"=>"2.7~9.8");

        $items[] = array("name"=>"心率", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"40~150","unit"=>"次/分钟","default"=>50);
        $items[] = array("name"=>"心律", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","unit"=>"","default"=>"正常");
        $items[] = array("name"=>"心音", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"肺部听诊", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"肝脏触诊", "parent_name"=>"内科","type"=> ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"脾脏触诊", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"肾脏叩诊", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"内科其它", "parent_name"=>"内科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");

        $items[] = array("name"=>"皮肤", "parent_name"=>"外科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"浅表淋巴结", "parent_name"=>"外科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"甲状腺-外科", "parent_name"=>"外科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"乳房", "parent_name"=>"外科","type"=> ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"脊柱", "parent_name"=>"外科","type"=> ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"四肢关节", "parent_name"=>"外科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"肛门、直肠指诊", "parent_name"=>"外科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        //&&&&&&&&&&&&

        $items[] = array("name"=>"裸视力-右", "parent_name"=>"眼科","type"=>  ReportService::RANGE,"option"=>"0~1.5","normal"=>"1.0","step"=>0.1,"default"=>1.0);
        $items[] = array("name"=>"裸视力-左", "parent_name"=>"眼科","type"=>  ReportService::RANGE,"option"=>"0~1.5","normal"=>"1.0","step"=>0.1,"unit"=>"","default"=>1.0);

        $items[] = array("name"=>"外耳", "parent_name"=>"耳鼻咽喉科","type"=>   ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"外耳道", "parent_name"=>"耳鼻咽喉科","type"=>   ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");
        $items[] = array("name"=>"鼓膜", "parent_name"=>"耳鼻咽喉科","type"=>  ReportService::SELECT,"option"=>"正常,异常","default"=>"正常");

        $items[] = array("name"=>"口腔粘膜", "parent_name"=>"口腔科","type"=>  ReportService::TEXT);
        $items[] = array("name"=>"牙齿", "parent_name"=>"口腔科","type"=>  ReportService::TEXT);
        $items[] = array("name"=>"唇", "parent_name"=>"口腔科","type"=>  ReportService::TEXT);
        
        /**妇科***/

        /*血常规*/
        $items[] = array("name"=>"红细胞计数", "parent_name"=>"血常规","type"=>  ReportService::RANGE,"option"=>"3.5~5.0","step"=>0.01,"normal"=>"3.5~5.0","unit"=>"T/L","default"=>"4.0");
        $items[] = array("name"=>"尿糖", "parent_name"=>"血常规","type"=>  ReportService::SELECT,"option"=>"阴性,阳性","default"=>"阴性");
//        $items[] = array("name"=>"尿白细胞", "parent_name"=>"血常规","type"=>   ReportService::SELECT,"option"=>"阴性,阳性","default"=>"阴性");
        $items[] = array("name"=>"尿亚硝酸盐", "parent_name"=>"血常规","type"=>   ReportService::SELECT,"option"=>"阴性,阳性","default"=>"阴性");
        $items[] = array("name"=>"蛋白质", "parent_name"=>"血常规","type"=>  ReportService::SELECT,"option"=>"阴性,阳性","default"=>"阴性");







        return $items;
    }
    
    

}
?>